#include "devicedelegate.h"
#include <KF5/BluezQt/bluezqt/device.h>
#include <KF5/BluezQt/bluezqt/devicesmodel.h>
#include <QPainter>
#include <QApplication>
DeviceDelegate::DeviceDelegate(QObject* parent):
    QAbstractItemDelegate(parent)
{

}

void DeviceDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    QStyleOptionViewItem opt = option;
    // initStyleOption(&opt, index);
    // 绘制背景和焦点状态
    painter->save();
    QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &opt, painter);
    // 获取设备数据
    const QString name = index.data(BluezQt::DevicesModel::NameRole).toString();
    const bool isConnected = index.data(BluezQt::DevicesModel::ConnectedRole).toBool();
    const bool isPaired = index.data(BluezQt::DevicesModel::PairedRole).toBool();
    const qint16 rssi = index.data(BluezQt::DevicesModel::RssiRole).toInt();
    // 定义绘制区域（留边距）
    QRect rect = opt.rect.adjusted(5, 5, -5, -5);

    // 绘制设备名称（粗体）
    painter->setFont(QFont("Arial", 10, QFont::Bold));
    painter->drawText(rect, Qt::AlignLeft | Qt::AlignTop, name);
    // 绘制状态信息（灰色）
    QString status = isConnected ? "Connected" : "Disconnected";
    QString status2 = isPaired ? "Paired" : "NotPair";
    if (rssi != 0)
    {
        status +=  QString(" | %1 | RSSI: %2").arg(status2).arg(rssi);
    }
    painter->setFont(QFont("Arial", 9));
    painter->setPen(Qt::gray);
    painter->drawText(rect, Qt::AlignLeft | Qt::AlignBottom, status);
    painter->restore();
}

QSize DeviceDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(index);
    return QSize(option.rect.width(), 40);
}
